<template>
  <div>
    <table border="1" width="700" style="border-collapse: collapse">
      <caption>
        购物车
      </caption>
      <thead>
        <tr>
          <th>
            <input type="checkbox" v-model="isChecked" /> <span>全选</span>
          </th>
          <th>名称</th>
          <th>价格</th>
          <th>数量</th>
          <th>总价</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <New
          v-for="(item, index) in goodList"
          :key="index"
          :name="item.name"
          :price="item.price"
          :num="item.num"
          :checked="item.checked"
          :index="index"
          @deleteBtn="deleteId"
          @changecheck="getcheck"
          @addnum="addAnum"
          @removenum="removeAnum"
        />
      </tbody>
      <tfoot>
        <tr>
          <td>合计:</td>
          <td colspan="5" style="text-align: center">{{ getallSum }}</td>
        </tr>
      </tfoot>
    </table>
  </div>
</template>

<script>
import New from "./components/Shopp.vue";
export default {
  data() {
    return {
      goodList: [
        {
          name: "诸葛亮",
          price: 1000,
          num: 1,
          checked: false,
        },
        {
          name: "蔡文姬",
          price: 1500,
          num: 1,
          checked: false,
        },
        {
          name: "妲己",
          price: 2000,
          num: 1,
          checked: false,
        },
        {
          name: "鲁班",
          price: 2200,
          num: 1,
          checked: false,
        },
      ],
    };
  },
  components: {
    New,
  },
  methods: {
    // 接收子组件传过来的索引
    removeAnum(index) {
      if (this.goodList[index].num > 0) this.goodList[index].num--;
    },
    //根据索引得知给哪一个数字+
    addAnum(index) {
      this.goodList[index].num++;
    },
    // 接收子组件传过来的索引，删除对应的
    deleteId(index) {
      this.goodList.splice(index, 1);
    },
    // 修改复选框的状态，实现双向绑定每一项的索引等于当前索引然后给checked的状态取反，就进行了更新
    getcheck(indexa) {
      const res = this.goodList.find((item, index) => index === indexa);
      res.checked = !res.checked;
    },
  },
  computed: {
    getallSum() {
      // 计算合计用reduce累计和方法 如果是选中状态返回总的 不然就是当前的价格
      return this.goodList.reduce((pre, item) => {
        if (item.checked) {
          return pre + item.price * item.num;
        } else {
          return pre;
        }
      }, 0);
    },
    // 计算全选按钮，如果当前父组件里的所有checked属性都为true是勾选
    isChecked: {
      get() {
        // 判断数组长度，防止数据全部被删除后全选按钮为选中状态
        if (this.goodList.length > 0) {
          return this.goodList.every((item) => item.checked);
        } else {
          return false;
        }
      },
      // val试图修改的值
      set(val) {
        this.goodList.forEach((item) => (item.checked = val));
      },
    },
  },
};
</script>

<style>
</style>